// pages/catalog/catalog.js
const villagersData = require('../../utils/villagers.js').villagers;

// 从本地文件获取动物数据
function mapVillagerData(raw, index) {
  // 性别字段适配：'♂'->'男'，'♀'->'女'
  var gender = raw['性别'] === '♂' ? '男' : (raw['性别'] === '♀' ? '女' : '未知');
  // 性格字段适配：去除血型后缀
  var personality = raw['性格'] ? raw['性格'].replace(/[AB型]/g, '') : '';

  // 检查 name 字段是否存在且不为空
  var name = raw['名称'] || raw['名字'] || raw['Name'] || '未知';

  // 构造云存储路径
  var cloudPath = 'cloud://cloud1-1gpyv55g5212b580.636c-cloud1-1gpyv55g5212b580-1363170652/image/' + name + '.png';

  return {
    id: index, // 使用索引作为ID
    name: name,
    image: cloudPath, // 使用云存储图片路径
    gender: gender,
    species: raw['种族'] || '未知',
    personality: personality || '其他'
  };
}

function getAllSpecies(villagers) {
  const set = new Set();
  villagers.forEach(v => {
    if (v['species']) set.add(v['species']);
  });
  return ['全部', ...Array.from(set)];
}

Page({
  data: {
    searchKey: '',
    genderOptions: ['全部', '男', '女'],
    speciesOptions: ['全部'],
    personalityOptions: ['全部', '元气', '悠闲', '暴躁', '自恋', '普通', '大姐姐', '运动', '成熟', '其他'],
    selectedGender: 0,
    selectedSpecies: 0,
    selectedPersonality: 0,
    animalList: [],
    showList: [],
    showGenderSheet: false,
    showSpeciesSheet: false,
    showPersonalitySheet: false,
  },

  onLoad: function() {
    // 从本地文件获取小动物数据
    this.loadAnimalData();
  },

  loadAnimalData: function() {
    wx.showLoading({ title: '加载中...' });
    
    try {
      // 批量导入小动物数据
      const animalList = villagersData.map((villager, index) => mapVillagerData(villager, index));
      console.log('获取到动物数据数量:', animalList.length);
      
      // 更新种族选项
      const speciesOptions = getAllSpecies(animalList);
      
      this.setData({ 
        animalList: animalList,
        speciesOptions: speciesOptions
      }, () => {
        this.updateShowList(); // 确保更新显示列表
        console.log('当前显示的动物列表数量:', this.data.showList.length);
      });
      
      wx.hideLoading();
    } catch (err) {
      wx.hideLoading();
      console.error('获取动物数据失败:', err);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  updateShowList() {
    const { animalList, searchKey, genderOptions, speciesOptions, personalityOptions,
      selectedGender, selectedSpecies, selectedPersonality } = this.data;
    let list = animalList.slice(); // 使用 slice 避免直接修改原数组
    
    // 分类筛选
    if (selectedGender > 0) {
      list = list.filter(item => item.gender === genderOptions[selectedGender]);
    }
    if (selectedSpecies > 0) {
      list = list.filter(item => item.species === speciesOptions[selectedSpecies]);
    }
    if (selectedPersonality > 0) {
      list = list.filter(item => item.personality === personalityOptions[selectedPersonality]);
    }
    // 搜索
    if (searchKey.trim()) {
      list = list.filter(item => item.name.indexOf(searchKey.trim()) !== -1);
    }
    console.log('筛选后的动物列表数量:', list.length);
    this.setData({ showList: list });
  },

  handleSearch(e) {
    this.setData({ searchKey: e.detail.value }, this.updateShowList);
  },

  onGenderChange(e) {
    this.setData({ selectedGender: e.detail.value }, this.updateShowList);
  },
  onSpeciesChange(e) {
    this.setData({ selectedSpecies: e.detail.value }, this.updateShowList);
  },
  onPersonalityChange(e) {
    this.setData({ selectedPersonality: e.detail.value }, this.updateShowList);
  },

  handleRefresh() {
    this.setData({
      searchKey: '',
      selectedGender: 0,
      selectedSpecies: 0,
      selectedPersonality: 0
    }, this.updateShowList);
  },

  goToDetail(e) {
    const name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: `/pages/villager/villager?name=${name}`
    });
  },

  onGenderTap() {
    this.setData({ showGenderSheet: true });
  },
  closeGenderSheet() {
    this.setData({ showGenderSheet: false });
  },
  selectGender(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ selectedGender: index, showGenderSheet: false }, this.updateShowList);
  },

  onSpeciesTap() {
    this.setData({ showSpeciesSheet: true });
  },
  closeSpeciesSheet() {
    this.setData({ showSpeciesSheet: false });
  },
  selectSpecies(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ selectedSpecies: index, showSpeciesSheet: false }, this.updateShowList);
  },

  onPersonalityTap() {
    this.setData({ showPersonalitySheet: true });
  },
  closePersonalitySheet() {
    this.setData({ showPersonalitySheet: false });
  },
  selectPersonality(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ selectedPersonality: index, showPersonalitySheet: false }, this.updateShowList);
  },

  stopPropagation() {},
});
